<?php

    /**
     * Currency
     */
    class currency {

        private $fxRate;
        private $keys = array();

        public function __construct($currency) {
            $url = 'http://download.finance.yahoo.com/d/quotes.csv?s='
                    . $currency['base'] . $currency['foreign'] . '=X&f=l1';

            $c = curl_init($url);
            curl_setopt($c, CURLOPT_HEADER, 0);
            curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
            $this->fxRate = doubleval(curl_exec($c));
            curl_close($c);
        }

        public function setKeys($keys) {
            $this->keys = $keys;
        }
        
        public function getRate() {
            return $this->fxRate;
        }

        
        public function convert($data) {

            if (empty($this->keys))
                die("Please set keys on currency class!");

            $type = gettype($data);

            switch ($type) {
                case 'array':

                    $newData = array();

                    foreach ($data as $key => $value) :
                        if (is_array($value) || is_object($value)) {
                            $newData[$key] = $this->convert($value);
                        } else {

                            if (in_array($key, $this->keys)):
                                $newData[$key] = ceil($value * $this->fxRate);
                            else:
                                $newData[$key] = $value;
                            endif;
                        }

                    endforeach;

                    break;

                case 'object':

                    $newData = new stdClass();

                    foreach ($data as $key => $value) :
                        if (is_array($value) || is_object($value)) {
                            $newData->{$key
                                    } = $this->convert($value);
                        } else {

                            if (in_array($key, $this->keys)):
                                $newData->{$key
                                        } = ceil($value * $this->fxRate);
                            else:
                                $newData->{$key
                                        } = $value;
                            endif;
                        }

                    endforeach;

                    break;
            }

            return $newData;
        }

    }

?>
